Cookie Management in Django

Manish Patel

Aug 25, 2023

1. Setting Cookies:

  • To set a cookie in a Django application, you typically use the HttpResponse object.
  • You can add cookies to the response headers using the set_cookie() method. For example:
from django.http import HttpResponse

response = HttpResponse("Cookie Set!")
response.set_cookie('username', 'john_doe', max_age=3600)  # Set the 'username' cookie with a lifespan of 1 hour (in seconds)
  • In this example, the set_cookie() method is used to add a cookie named ‘username’ with the value ‘john_doe’ and a maximum age of 3600 seconds (1 hour).

2. Reading Cookies:

  • When a user sends a request to your Django application, the cookies associated with that request are automatically included in the request.COOKIES dictionary.
  • You can access the values of cookies using this dictionary. For example:
def get_username(request):
   username = request.COOKIES.get('username', 'Guest')
   return f"Hello, {username}!"
  • In this example, the get() method is used to retrieve the value of the ‘username’ cookie from the request.COOKIES dictionary. If the cookie is not present, it defaults to ‘Guest’.

3. Updating Cookies:

  • If you need to update the value or other attributes of a cookie, you can set a new cookie with the same name.
  • The new cookie will overwrite the previous one. For example:
response = HttpResponse("Cookie Updated!")
response.set_cookie('username', 'new_username', max_age=3600)

4. Deleting Cookies:

  • To remove a cookie from the user’s browser, you can set its value to an empty string and specify an expiration time in the past.
  • This effectively tells the browser to delete the cookie. For example:
response = HttpResponse("Cookie Deleted!")
response.set_cookie('username', '', expires='Thu, 01 Jan 1970 00:00:00 GMT')
  • Setting the expiration date in the past causes the browser to remove the cookie.
  • Cookies are not suitable for storing sensitive information as they are stored in plain text on the user’s browser.
  • For sensitive data, consider using Django’s session management or other secure mechanisms.

Step 1: Set Up a Django Project

If you haven’t already, install Django:

pip install Django

Create a new Django project:

django-admin startproject cookiedemo
cd cookiedemo

Step 2: Create an App

Now, let’s create a new app within the project:

python manage.py startapp student
  • Register app in settings

Step 3: Define URL Patterns

In the cookiedemo directory, create a file named urls.py to define your URL patterns:


from django.contrib import admin
from django.urls import path
from student import views

urlpatterns = [
    path("admin/", admin.site.urls),
    path("set/", views.setcookie),
    path("get/", views.getcookie),
    path("del/", views.delcookie),
]

Step 4: Create Views

In the same student directory, modify the file named views.py to define your views:

from django.shortcuts import render

# Create your views here.
def setcookie(request):
    response = render(request, 'student/setcookie.html')
    response.set_cookie('name', 'ParleG', max_age=60)
    return response

def getcookie(request):
    #name = request.COOKIES['name'] 
    name = request.COOKIES.get('name', "Guest") # no error and Guest return if key not present
    return render(request, 'student/getcookie.html', {'name': name})
def delcookie(request):
    response = render(request, 'student/delcookie.html')
    response.delete_cookie('name')
    return response

SETCOOKIE HTML

templates/student/setcookie.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Set cookie</title>
</head>
<body>
    <h1>Cookie is set</h1>
</body>
</html>

GETCOOKIE HTML

templates/student/getcookie.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Getcookie</title>
</head>
<body>
    <h1>Got the cookie </h1>
    {{ name }}
</body>
</html>

DELCOOKIE HTML

templates/student/delcookie.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Delete cookie</title>
</head>
<body>
    <h1>Cookie deleted</h1>
</body>
</html>

Step 6: Run the Server

Now you can run the development server:

python manage.py runserver

Visit these URLs in your browser to see the different views:

  • Set Cookie: http://127.0.0.1:8000/set/
  • Get Cookie: http://127.0.0.1:8000/get/
  • Del Cookie: http://127.0.0.1:8000/del/

Check the developer tool of google chrome to check the cookie status